import router from './router'
import {checkAuthToken} from '@/utils/auth'
import NProgress from 'nprogress'
import store from './store'
// 白名单
const whiteList = ['/login', '/welcome']
router.beforeEach((to, from, next) => {
  // console.log('-->to', to)
  // console.log('-->from', from)
  NProgress.start()
  const userInfo = store.getters.userInfo
  let loadAsyncRouterFlag = store.getters.loadAsyncRouterFlag
  if (checkAuthToken()) {
    if (to.path === '/login') {
      next({path: '/'})
      NProgress.done()
    } else {
      if (!loadAsyncRouterFlag) { // 判断当前用户是否获取权限
        store.commit('user/SET_LOADASYNCROUTER_FLAG', true)
        if (userInfo && Object.getOwnPropertyNames({...userInfo}).length > 0) {
          getUserAccessRight(to, next, userInfo)
        } else {
          store.dispatch('user/GetLoginInfo').then(info => { // 获取登录信息
            getUserAccessRight(to, next, info.userInfo)
          }).catch(errr => {
            store.commit('user/SET_LOADASYNCROUTER_FLAG', false)
            toLogout(errr, next, to)
          })
        }
      } else {
        if (to.path === '/404' && from.path === '/login') {
          next({path: '/'})
        } else {
          next()
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      if (to.query) {
        from.meta.keepAlive = false
      }
      next()
    } else {
      next(`/login`)
      NProgress.done()
    }
  }
})
router.onError((error) => {
  const pattern = /Loading chunk (\d)+ failed/g
  const isChunkLoadFailed = error.message.match(pattern)
  const targetPath = router.history.pending.fullPath
  if (isChunkLoadFailed) {
    router.replace(targetPath)
  }
})
router.afterEach(() => {
  NProgress.done() // 结束Progre
})

function getUserAccessRight (to, next, userInfo) {
  const positions = userInfo.positions
  const authInfo = store.getters.authInfo
  if (positions && positions.length > 0) {
    if (authInfo && Object.getOwnPropertyNames({...authInfo}).length > 0) {
      // 根据用户访问权限获取动态路由
      store.dispatch('permission/GenerateAccessRouters', authInfo).then(() => {
        const routers = store.getters.addRouters
        router.addRoutes(routers)// 添加动态路由
        if (to.path === '/404') {
          next({
            path: to.redirectedFrom || '/',
            replace: true
          })
        } else {
          next({
            ...to,
            replace: true
          })
        }
      })
    } else {
      let positionCode = userInfo.loginPosition
      // 根据用户信息和用户职位信息 获取访问权限
      store.dispatch('user/GetUserMenuInfo', {employeeCode: userInfo.userId, positionCode}).then(menus => {
        if (menus && Object.getOwnPropertyNames({...menus}).length > 0) {
          // 根据用户访问权限获取动态路由
          store.dispatch('permission/GenerateAccessRouters', menus).then(() => {
            const routers = store.getters.addRouters
            if (routers && routers.length > 0) {
              routers.forEach(item => {
                router.addRoute(item)
              })
            }
            // router.addRoutes(routers) // 添加动态路由
            if (to.path === '/404') {
              next({
                path: to.redirectedFrom || '/',
                replace: true
              })
            } else {
              next({
                ...to,
                replace: true
              })
            }
          })
        } else {
          next({
            path: '/weclome',
            replace: true
          })
        }
      }).catch((errr) => {
        store.commit('user/SET_LOADASYNCROUTER_FLAG', false)
        toLogout(errr, next, to)
        // NProgress.done()
      })
    }
  } else {
    // 未配置职位-定位到欢迎页面
    next({
      path: '/weclome',
      replace: true
    })
    NProgress.done()
  }
}

function toLogout (error, next, to, time = 5) {
  let msg = '请求异常，需重新登录'
  if (error) {
    if (error.response && error.response.status === 401) {
      msg = '您的账号登录已失效，请重新登录'
    }
  }
  window.app.$msgBox.delayeOff('提示', msg, () => {
    store.dispatch('user/Logout').then(() => {
      if (to.redirectedFrom) {
        next({path: `/login?redirect=` + to.redirectedFrom})
      } else {
        next(`/login`)
      }
    })
  }, time, 'warning')
}
